package com.gxa.medical.controller;

import com.gxa.medical.pojo.User;
import com.gxa.medical.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
@Controller
public class ExportController {
    @Autowired
    private UserService userService;
    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<User> users =null;
        // 工作簿对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建工作表
        HSSFSheet sheet = workbook.createSheet("用户列表");
        String fileName = "用户列表.xls";
        // 将文件名中的中文部分被URL编码后的内容进行解析, 最终还是显示为中文状态
        fileName = URLEncoder.encode(fileName, "utf-8").replaceAll("\\+", "%20");
        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = {"编号", "昵称", "手机号", "注册时间"};
        // 创建一个行对象, 作为表头
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            // 在行中添加单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            // 把字段名添加到表头行上
            cell.setCellValue(text);
        }
        //准备将时间格式处理为标准日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 添加数据行:
        int rowNum = 1;
        for (User item : users) {
            HSSFRow dataRow = sheet.createRow(rowNum);
            dataRow.createCell(0).setCellValue(rowNum);
            dataRow.createCell(1).setCellValue("");
            dataRow.createCell(2).setCellValue(item.getPhone());
            dataRow.createCell(3).setCellValue(dateFormat.format("item.getRegTime()"));
            rowNum++;
        }
        //返回给前端下载
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }
}
